const router = require('koa-router')(),
      config = require('../config/config.json');

const blogListData = {
  'blogId': 1,
  'title': 1,
  'htmlContent': 1,
  '_id': 0
};

const blogData = {
  'title': 1,
  'htmlContent': 1,
  'category': 1,
  'releaseDate': 1,
  '_id': 0
};

/* when get root redirect to blogs-list */
router.get('/', async (ctx, next) => {
  const data = {},
    postsPerFragment = (await ctx.mongo.db(config.dbname)
      .collection('configs')
      .findOne({ 'primaryKey': 'config' }))
      .postsPerFragment;

  let posts = (await ctx.mongo.db(config.dbname)
    .collection('article')
    .find({}, { projection: blogListData })
    .sort({ blogId: -1 })
    .toArray());

  const postsLen = posts.length,
    postsTitle = [];

  postsPerFragment >= posts.length
    ? null
    : (data.next = '/fragment/2');

  posts = posts.splice(0, postsPerFragment);
  posts.forEach(item => {
    postsTitle.push(item.title);
    let pos = item.htmlContent.indexOf('<a id="more"></a>');
    pos > -1 ? null : (pos = item.htmlContent.indexOf('<p>@@</p>'));
    item.htmlContent = item.htmlContent.slice(0, pos);
  });

  data.blogs = posts;
  data.htmlTitle = 'page | Fragment';
  data.htmlKeywords = `博客列表, page1 | Fragment`;
  // SEO description.length is bwteen 25 to 160 chars.
  data.htmlDescription = `博客列表 ${postsTitle.join(',').substr(0, 155)}`;

  await ctx.render('user/fragment.njk', { data });
});

/* get '/fragment', maximum show news 'postsPerFragment' blogs */
router.get('/fragment', async (ctx, next) => {
  const data = {},
    postsPerFragment = (await ctx.mongo.db(config.dbname)
      .collection('configs')
      .findOne({ 'primaryKey': 'config' }))
      .postsPerFragment;

  let posts = (await ctx.mongo.db(config.dbname)
    .collection('article')
    .find({}, { projection: blogListData })
    .sort({ blogId: -1 })
    .toArray());

  const postsLen = posts.length,
    postsTitle = [];

  postsPerFragment >= posts.length
    ? null
    : (data.next = '/fragment/2');

  posts = posts.splice(0, postsPerFragment);
  posts.forEach(item => {
    postsTitle.push(item.title);
    let pos = item.htmlContent.indexOf('<a id="more"></a>');
    pos > -1 ? null : (pos = item.htmlContent.indexOf('<p>@@</p>'));
    item.htmlContent = item.htmlContent.slice(0, pos);
  });

  data.blogs = posts;
  data.htmlTitle = 'page | Fragment';
  data.htmlKeywords = `博客列表, page1 | Fragment`;
  data.htmlDescription = `博客列表 ${postsTitle.join(',').substr(0, 155)}`;

  await ctx.render('user/fragment.njk', { data });
});

router.get('/fragment/:page', async (ctx, next) => {
  const page = parseInt(ctx.params.page),
    data = {};

  if (page > 0 && !isNaN(page)) {
    const postsPerFragment = (await ctx.mongo.db(config.dbname)
      .collection('configs')
      .findOne({ 'primaryKey': 'config' }))
      .postsPerFragment;

    let posts = (await ctx.mongo.db(config.dbname)
      .collection('article')
      .find({}, { projection: blogListData })
      .sort({ blogId: -1 })
      .toArray());

    const postsLen = posts.length,
      postsTitle = [];

    if ((postsPerFragment * (page - 1)) < postsLen) {
      posts = posts.splice((postsPerFragment * (page - 1)), postsPerFragment);
      posts.forEach(item => {
        postsTitle.push(item.title);
        let pos = item.htmlContent.indexOf('<a id="more"></a>');
        pos > -1 ? null : (pos = item.htmlContent.indexOf('<p>@@</p>'));
        item.htmlContent = item.htmlContent.slice(0, pos);
      });

      page > 1 ? data.previous = `/fragment/${page - 1}` : null;
      postsPerFragment * page < postsLen ? data.next = `/fragment/${page + 1}` : null;
      data.blogs = posts;
      data.htmlTitle = `page${page} | Fragment`;

      data.htmlTitle = 'page | Fragment';
      data.htmlKeywords = `博客列表, page${page} | Fragment`;
      data.htmlDescription = `博客列表 ${postsTitle.join(',').substr(0, 155)}`;

      await ctx.render('user/fragment.njk', { data });
    } else {
      ctx.redirect('/404');
    }
  } else {
    ctx.redirect('/404');
  }
});

router.get('/post/:blogId', async (ctx, next) => {
  const blogId = parseInt(ctx.params.blogId);
  let data = null;

  if (blogId > 0 && !isNaN(blogId)) {
    const blog = (await ctx.mongo.db(config.dbname)
      .collection('article')
      .findOne({ 'blogId': blogId }, { projection: blogData }));
    if (blog) {
      blog.htmlContent = blog.htmlContent.replace(/(<a id="more"><\/a>)|(<p>@@<\/p>)/g, '')
      data = blog;
      data.htmlTitle = data.title;
      data.htmlKeywords = `${data.title},${data.category}`;
      data.htmlDescription = `${data.title},${data.category},${data.htmlContent.substr(0, 100).replace(/(<.+?>)|(\s)/g, '')}`;

      await ctx.render('user/post.njk', { data });
    } else {
      ctx.redirect('/404');
    }
  } else {
    ctx.redirect('/404');
  }
});

router.get('/category', async (ctx, next) => {
  const data = {};
  data.htmlTitle = `博客分类`;
  data.htmlKeywords = `博客分类`;
  data.title = `博客分类`;
  data.links = [],
    blogCategorys = [];
  const categorys = await ctx.mongo.db(config.dbname)
    .collection('category')
    .find({}).toArray();
  categorys.forEach(item => {
    if (item.blogs.length > 0) {
      blogCategorys.push(item.name);
      data.links.push({ name: item.name, href: `/category/${item.name}` })
    }
  });

  data.htmlDescription = `博客分类:${blogCategorys.join(',').substr(0, 155)}`;

  await ctx.render('user/category.njk', { data });
});

router.get('/category/:categoryName', async (ctx, next) => {
  const categoryName = ctx.params.categoryName,
    data = {};
  data.htmlTitle = `博客列表 | ${categoryName}`;
  data.htmlKeywords = `${categoryName},博客分类`;
  data.title = categoryName;
  data.links = [],
    blogCategoryTitles = [];

  const categoryblogs = await ctx.mongo.db(config.dbname)
    .collection('category')
    .findOne({ 'name': categoryName });

  if (categoryblogs) {
    categoryblogs.blogs.forEach(item => {
      blogCategoryTitles.push(item.title);
      data.links.push({ name: item.title, href: `/post/${item.blogId}` });
    });

    data.htmlDescription = `${categoryName} ${blogCategoryTitles.join(',').substr(0, 140)}`;
    await ctx.render('user/category.njk', { data });
  } else {
    ctx.redirect('/404');
  }
});

router.get('/user/*', async (ctx, next) => {
  ctx.set('Cache-Control', `max-age=${3 * 60 * 60}`);
  await next();
});
module.exports = router;
